package com.share.shareplatform.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.share.shareplatform.pojo.exception.LogicException;
import lombok.Data;

import java.util.*;

@Data
public class Result {
    private int code;
    private HashMap<String ,Object> result=new HashMap<>();
    private String message;

    public Result(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public Result(){

    }

    public static Result getInstance(int code, String message){
        return new Result(code,message);
    }

    public Result put(String name , Object o){
        result.put(name,o);
        return this;
    }

    public static <T> T getResultValue(Result result,String resultKey,Class<T> c){

        Object o = result.getResult().get(resultKey);
        if(o!=null){
             return JSON.parseObject(JSON.toJSONString(o), c);
        }
        return null;
    }

    public static <T> List<T> getListResultValue(Result result,Class<T> c){

        List list = (List)result.getResult().get("list");
        if(list!=null){
            List<T> resultList=new ArrayList<>(list.size());
            for(Object o: list){
                T t = JSON.parseObject(JSON.toJSONString(o), c);
                resultList.add(t);
            }
            return resultList;
        }
        return null;
    }

    public static <K,V> Map<K,V> getMapResultValue(Result result,Class<K> k,Class<V> v){
        Map map=(Map)result.getResult().get("map");
        if(map!=null){
            Map<K,V> resultMap=new HashMap<>(map.size());
            Set<Map.Entry> set = map.entrySet();
            for(Map.Entry entry:set){
                resultMap.put(JSON.parseObject(JSON.toJSONString(entry.getKey()),k),
                        JSON.parseObject(JSON.toJSONString(entry.getValue()),v));
            }
            return resultMap;
        }
        return null;
    }



}
